package com.dacool.http;

import java.io.IOException;
import java.util.HashMap;

import org.apache.http.ParseException;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.dacool.config.Config;
import com.dacool.http.HttpTool.Response;
import com.dacool.util.ViewUtils;

public abstract class BaseRequest {

	public static interface ResponseHandler {
		public void handleResponse(BaseRequest request, int statusCode,
				String errorMsg, String response);
	}

	private HashMap<String, Object> params = new HashMap<String, Object>();

	private ResponseHandler handler;

	/**
	 * 子类override该方法用于设置访问url
	 * 
	 * @return
	 */
	protected abstract String url();

	/**
	 * 用于子类设置请求参数
	 * 
	 * @param map
	 */
	protected abstract void generateParams(HashMap<String, Object> map);

	public BaseRequest setHandler(ResponseHandler handler) {
		this.handler = handler;
		return this;
	}

	protected boolean isGet() {
		return false;
	}

	public void start() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					generateParams(params);
					if (params.keySet().isEmpty()) {
						long timemillis = System.currentTimeMillis();
						params.put("rd", timemillis);
					}
					Response response = isGet() ? HttpTool.getRequest(String
							.format("%s%s", Config.sharedConfig().getHost(),
									url(), needSaveCookie()), params,
							needSaveCookie()) : HttpTool.postRequst(String
							.format("%s%s", Config.sharedConfig().getHost(),
									url(), needSaveCookie()), params,
							needSaveCookie());
//					Log.d("test", "request:" + url() + ",response:"
//							+ response.data);
					try {
						JSONObject returnJson = new JSONObject(response.data);
						int code = returnJson.optInt("code", 0);
//						Log.d("test", "code " + code);
						if (code == 105) {
							ViewUtils.login();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					if (handler != null)
						handler.handleResponse(BaseRequest.this,
								response.statusCode, null, response.data);
				} catch (Exception e) {

					if (handler != null)
						handler.handleResponse(BaseRequest.this, -1, "通讯出错", "");
					e.printStackTrace();
				}
			}
		}).start();

	}

	protected boolean needSaveCookie() {
		return true;
	}
}
